package JavaEE_notes.common_API.Network;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * @author TaiZai
 * @data 2024/9/26 14:54
 */
public class ClientReaderThread extends Thread {
    private Socket socket;
    public ClientReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            while (true) {
                try {
                    String msg = dis.readUTF();
                    System.out.println(msg + "-来自" + socket.getRemoteSocketAddress());
                    // 把消息分发给全部客户端进行接收
                } catch (Exception e) {
                    System.out.println("自己下线了：" + socket.getLocalSocketAddress());
                    dis.close();
                    socket.close();
                    e.printStackTrace();
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
